import React, { Component } from "react";
import {
  StyleSheet,
  View,
  Text,
  Image,
  SectionList,
  TouchableOpacity
} from "react-native";
import Toast from "react-native-simple-toast";
import { connect } from "react-redux";
import HeaderDefault from "../../components/header/HeaderDefault";
import { theme_app, theme_text } from "../../utils/appTheme";

import { submitExeTask } from "../../netServer/advicePerform";
import { birthdayToAges, dateTransform } from "../../utils/utils_date";

class OralPerform extends Component {
  constructor(props) {
    super(props);
    this.state = {
      advList: [],
      adv_pending: [],
      adv_Processed: [],
      updateSeletedStatus: 1,
      isSeletedAll: false
    };
  }
  static navigationOptions = ({ navigation }) => ({
    header: <HeaderDefault backBtnOnPress={navigation.goBack} title="口服药" />
  });

  componentDidMount() {
    let { taskList = [] } = this.props.navigation.state.params.taskMain;
    this._handeleNetData(taskList);
  }

  _handeleNetData = data => {
    // console.log("345", data);
    let temArr1 = [];
    let temArr2 = [];

    data.forEach(element => {
      if (element.status === "待执行") {
        temArr1.push(element);
      } else {
        temArr2.push(element);
      }
    });

    this.setState({
      advList: data ? data : [],
      adv_pending: temArr1,
      adv_Processed: temArr2
    });
  };
  _renderItem = taskMain => {
    let { patient = {} } = taskMain;
    const item = patient;
    let sexName = "";
    if (item.sex == 1) {
      sexName = "男";
    } else if (item.sex == 2) {
      sexName = "女";
    }
    return (
      <View
        style={{
          width: screenWidth,
          height: 80,
          flexDirection: "row",
          borderBottomColor: "#efefef",
          borderBottomWidth: 1,
          backgroundColor: "white",
          paddingLeft: 10,
          paddingRight: 10
        }}
      >
        <View style={{ width: screenWidth - 120, height: 80 }}>
          <View style={styles.lineStyle}>
            <Text style={{ fontSize: 16 }}>{item.name}</Text>

            <Text style={{ marginLeft: 25 }}>
              {sexName}/{birthdayToAges(item.birthday)}
            </Text>

            <Text style={{ marginLeft: 25 }}>{item.bed_no}</Text>
          </View>

          <View style={styles.lineStyle}>
            <Text style={{ width: 150 }}>诊断：{item.diagnose}</Text>

            <Text
              style={{
                marginLeft: 25,
                color: "red",
                width: screenWidth - 200
              }}
            >
              {item.posAllergy}
            </Text>
          </View>
        </View>

        <View style={{ width: 100, height: 80, flexDirection: "row" }}>
          <View
            style={{
              width: 40,
              height: 80,
              justifyContent: "center",
              alignItems: "center"
            }}
          />
          <View
            style={{
              width: 60,
              height: 80,
              justifyContent: "center",
              alignItems: "center"
            }}
          >
            <Text style={{ fontSize: 20 }}>
              {/* {item.hasAdvNum}/{item.totalAdvNum} */}
            </Text>
          </View>
        </View>
      </View>
    );
  };

  _renderFlistItem = ({ item, index, section }) => {
    let seletIcon = item.isSeleted
      ? require("./src/xuanze1.png")
      : require("./src/xuanze.png");
    let userName = "";
    let freqCode = "";

    return (
      <View
        style={{
          width: screenWidth,
          borderBottomColor: "#efefef",
          borderBottomWidth: 1,
          backgroundColor: "white",
          flexDirection: "row"
        }}
      >
        <View
          style={{
            paddingLeft: 10,
            paddingRight: 10,
            width: 0.6 * screenWidth,
            flexDirection: "row",
            alignItems: "center"
          }}
        >
          {item.status === "待执行" ? (
            <TouchableOpacity
              style={{
                width: 40,
                height: 40,
                justifyContent: "center",
                alignItems: "center"
              }}
              onPress={() => {
                item.isSeleted = !item.isSeleted;
                this._freshSeletedStatus();
              }}
            >
              <Image style={{ width: 30, height: 30 }} source={seletIcon} />
            </TouchableOpacity>
          ) : null}

          <View style={{ flex: 1 }}>
            {item.advList.map((value, index) => {
              userName = value.usageName;
              freqCode = value.freqCode;

              let status_name = value.status_name;

              return (
                <View
                  style={{
                    borderBottomColor: "#f1f1f1",
                    borderBottomWidth: 1,
                    paddingLeft: 10
                  }}
                  key={index}
                >
                  <Text style={{ paddingBottom: 5, paddingTop: 5 }}>
                    {value.medName}&nbsp;&nbsp;
                    <Text style={{ color: "red" }}>
                      {status_name === "进行中" ? "" : status_name}
                    </Text>
                  </Text>
                  <Text style={{ paddingBottom: 5, paddingTop: 5 }}>
                    {value.standard}/{value.use_unit} &nbsp;&nbsp;
                    {value.measure}
                  </Text>
                </View>
              );
            })}
          </View>
        </View>
        <View
          style={{
            flex: 1,
            flexDirection: "row",
            alignItems: "center"
          }}
        >
          <Text>{userName}</Text>

          <Text>&nbsp;&nbsp;&nbsp;&nbsp;{freqCode}</Text>

          <Text>
            &nbsp;&nbsp;&nbsp;&nbsp;
            {this._getTime(item.use_time)}
          </Text>
        </View>
      </View>
    );
  };

  _getTime(use_time) {
    let dt = use_time ? new Date(use_time.replace(/-/g, "/")) : null;

    return dt ? dateTransform(dt, "hh:mm") : null;
  }

  _freshSeletedStatus = () => {
    let marr = this.state.updateSeletedStatus + 1;
    let isAllSelet = true;

    this.state.adv_pending.forEach(element => {
      if (!element.isSeleted) {
        isAllSelet = false;
      }
    });

    this.setState({
      updateSeletedStatus: marr,
      isSeletedAll: isAllSelet && this.state.adv_pending.length !== 0
    });
  };

  _controlSeletedStatu = () => {
    this.state.adv_pending.forEach(element => {
      element.isSeleted = !this.state.isSeletedAll;
    });

    this._freshSeletedStatus();
  };
  // paramss.append('data[' + index + '][name]', element.name)
  _commitAdv = () => {
    // mainid
    let params = new FormData();

    let { user_id } = this.props.user_info;
    params.append("userId", user_id);

    // taskid
    let tempASrr = [];
    let isBreackStr = null;
    let markIndx = 0;

    for (let index = 0; index < this.state.adv_pending.length; index++) {
      const element = this.state.adv_pending[index];

      if (element.isSeleted) {
        let { main_task_id, task_id } = element;

        let jsonItem = {
          mainTaskId: main_task_id,
          taskId: task_id
        };

        // asd
        element.advList.forEach(elements => {
          if (elements.status_name !== "进行中") {
            isBreackStr = elements.status_name;
          }
        });

        tempASrr.push(jsonItem);

        params.append("taskData[" + markIndx + "][mainTaskId]", main_task_id);
        params.append("taskData[" + markIndx + "][taskId]", task_id);

        markIndx++;
      }
    }

    if (isBreackStr) {
      let art = `医嘱${isBreackStr}`;
      Toast.showWithGravity(art, 0.3, Toast.CENTER);

      return;
    }

    if (tempASrr.length > 0) {
      // return;
      submitExeTask(params, resp => {
        let { code, msg } = resp;

        if (code == "0") {
          Toast.showWithGravity("数据提交成功", 0.3, Toast.CENTER);
          this._commitAdvSuccess(tempASrr);
        } else {
          Toast.showWithGravity(msg, 0.3, Toast.CENTER);
        }
      });
    } else {
      Toast.showWithGravity("请选择您要执行的口服药", 0.3, Toast.CENTER);
      return;
    }
  };

  _commitAdvSuccess = commitArr => {
    let adv_t_pendding = [];
    let adv_t_Processed = this.state.adv_Processed.concat([]);
    this.state.adv_pending.forEach(element => {
      var found = commitArr.find(function (isHav) {
        return (
          isHav.mainTaskId === element.main_task_id &&
          isHav.taskId === element.task_id
        );
      });

      if (found) {
        element.status = "已执行";
        adv_t_Processed.push(element);
      } else {
        adv_t_pendding.push(element);
      }
    });

    this.setState({
      adv_Processed: adv_t_Processed,
      adv_pending: adv_t_pendding
    });
    this._freshSeletedStatus();
  };

  _keyExtractor = (item, index) => item.task_id + "task";

  _separator = () => {
    return <View style={{ height: 1, backgroundColor: "#efefef" }} />;
  };

  render() {
    let seletIcon = this.state.isSeletedAll
      ? require("./src/xuanze1.png")
      : require("./src/xuanze.png");
    return (
      <View style={styles.container}>
        {this._renderItem(this.props.navigation.state.params.taskMain)}

        <SectionList
          style={{ flex: 1 }}
          renderItem={this._renderFlistItem}
          renderSectionHeader={({ section: { title } }) => (
            <View
              style={{
                width: screenWidth,
                height: 50,
                backgroundColor: "white",
                borderBottomWidth: 1,
                borderBottomColor: "#efefef",
                paddingLeft: 10,
                paddingRight: 10,
                flexDirection: "row",
                justifyContent: "space-between",
                alignItems: "center"
              }}
            >
              <Text style={{ fontWeight: "bold" }}>{title}</Text>
              <Image
                style={{ width: 25, height: 25 }}
                source={require("./src/jiantou.png")}
              />
            </View>
          )}
          sections={[
            { title: "未执行", data: this.state.adv_pending },
            { title: "已执行", data: this.state.adv_Processed }
          ]}
          extraData={this.state.updateSeletedStatus}
          keyExtractor={(item, index) => item + index}
        />

        <View
          style={{
            width: screenWidth,
            height: 45,
            borderTopColor: "#9b9b9b",
            borderTopWidth: 1,
            flexDirection: "row"
          }}
        >
          <TouchableOpacity
            onPress={this._controlSeletedStatu}
            style={{
              width: 60,
              height: 45,
              borderRightColor: "#9b9b9b",
              borderRightWidth: 1,
              justifyContent: "center",
              alignItems: "center"
            }}
          >
            <Image style={{ width: 30, height: 30 }} source={seletIcon} />
          </TouchableOpacity>
          <TouchableOpacity
            onPress={this._commitAdv}
            style={{
              width: screenWidth - 60,
              height: 45,
              justifyContent: "center",
              alignItems: "center"
            }}
          >
            <Text style={{ fontSize: 16, color: "#880000" }}>提交</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: theme_app.bg_color
  },
  lineStyle: {
    width: screenWidth - 120,
    height: 40,
    flexDirection: "row",
    alignItems: "center"
  }
});

function select(store) {
  return { user_info: store.userInfo.user_info };
}

export default connect(select)(OralPerform);
